<?php

namespace App\HttpController\V1;

use EasySwoole\Http\AbstractInterface\Controller;

class Base extends Controller
{

    function index()
    {
        // TODO: Implement index() method.
        $this->actionNotFound( 'index' );
    }

    function onRequest( ?string $action ): ?bool
    {
        $allow_origin = array(
            WEB_URL,
            ADMIN_URL,
            'http://www.xiaoyaoji.cn',
            'http://localhost:8080',
            'http://192.168.1.125:8080',
            'http://192.168.1.125:8080/',
            'http://192.168.1.120:8080',
            'http://192.168.1.120:8080/'
        );
        $origin = $this->request()->getHeader( "origin" );
        if ( is_array( $origin )  && count($origin)>0) {
            $origin = $origin[0];
        }
        if ( in_array( $origin, $allow_origin ) ) {

            $this->response()->withHeader( 'Access-Control-Allow-Origin', $origin );
//        } else {
//            return false;
        }
        // TODO: Implement onRequest() method.
        $this->response()->withHeader( 'Access-Control-Allow-Methods', 'GET, POST' );
        $this->response()->withHeader( 'Access-Control-Allow-Credentials', 'true' );
        $this->response()->withHeader("Access-Control-Allow-Headers", "Content-Type,Set-Cookie,token_name");
        $this->response()->withHeader("Access-Control-Expose-Headers", "Content-Type,Set-Cookie,token_name");
        $this->response()->withHeader("Access-Control-Request-Headers", "Content-Type,Set-Cookie,token_name");
        return parent::onRequest( $action ); // TODO: Change the autogenerated stub
    }


    protected function input( string $name = "", string $method = null )
    {
        if ( empty( $method ) ) {
            $data = array_merge( $this->request()->getParsedBody(), $this->request()->getQueryParams() );
        } else {
            $method = strtolower( $method );
            if ( $method == 'post' ) {
                $data = $this->request()->getParsedBody();
            } elseif ( $method == 'get' ) {
                $data = $this->request()->getQueryParams();
            }
        }
        if ( $name != "" ) {
            $search = explode( ',', $name );
            $res = [];
            foreach ( $search as $item ) {
                $res[ $item ] = $data[ $item ] ?? null;
            }
            if ( count( $search ) == 1 ) {
                $res = array_shift( $res );
            }
            $data = $res;
        }
        return $data;
    }

    public function getPage()
    {
        $page = $this->input( 'page', 'get' ) ?? 1;
        $limit = 10;
        return [
            ( $page - 1 ) * $limit,
            $limit
        ];
    }
}